package daily;

import org.apache.commons.lang.math.RandomUtils;

public class ThreadLocalTest {
	
	public static void main(String[] args) {
		new Thread(new Runnable(){

			@Override
			public void run() {
				int data=RandomUtils.nextInt(10000);
				MyThreadData.getInstance().setName(Thread.currentThread().getName());
				MyThreadData.getInstance().setAge(data);
				System.out.println("Thread name:"+Thread.currentThread().getName()+" put name:"+Thread.currentThread().getName()+" age:"+data);
				new A().get();
				new B().get();
			}
			
		}).start();
		
		new Thread(new Runnable(){

			@Override
			public void run() {
				int data=RandomUtils.nextInt(10000);
				MyThreadData.getInstance().setName(Thread.currentThread().getName());
				MyThreadData.getInstance().setAge(data);
				System.out.println("Thread name:"+Thread.currentThread().getName()+" put name:"+Thread.currentThread().getName()+" age:"+data);
				new A().get();
				new B().get();
			}
			
		}).start();
	}
	
	static class A{
		public void get(){
			System.out.println("A from "+Thread.currentThread().getName()+" get name"+MyThreadData.getInstance().getName()+" ,age:"+MyThreadData.getInstance().getAge());
		}
	}
	
	static class B{
		public void get(){
			System.out.println("B from "+Thread.currentThread().getName()+" get name"+MyThreadData.getInstance().getName()+" ,age:"+MyThreadData.getInstance().getAge());
		}
	}


}
class MyThreadData{
	private  static ThreadLocal<MyThreadData> threadDatas=new ThreadLocal<MyThreadData>();
	private MyThreadData(){
			
	}
	public  static  MyThreadData getInstance(){
		if(threadDatas.get()==null){
			threadDatas.set(new MyThreadData());
		}
		return threadDatas.get();
	}
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}